terraform {
  backend "azurerm" {
    storage_account_name = {{ .Values.Context.StorageAccount | quote }}
    resource_group_name = {{ .Values.ResourceGroup | quote }}
    container_name = {{ .Values.Bucket | quote }}
    key = "{{ .Values.__CLUSTER__ }}/{{ .Values.Prefix }}/terraform.tfstate"
  }

  required_providers {
    azurerm = {
      source = "hashicorp/azurerm"
      version = "~> 3.46.0"
    }
    kubernetes = {
      source  = "hashicorp/kubernetes"
      version = "~> 2.18.1"
    }
  }
}

provider "azurerm" {
  features {}
}

{{ if .Values.ClusterCreated }}
provider "kubernetes" {
  host                   = {{ .Values.Cluster }}.host
  client_certificate     = base64decode({{ .Values.Cluster }}.client_certificate)
  client_key             = base64decode({{ .Values.Cluster }}.client_key)
  cluster_ca_certificate = base64decode({{ .Values.Cluster }}.cluster_ca_certificate)
}
{{ else }}
data "azurerm_kubernetes_cluster" "cluster" {
  name = {{ .Values.Cluster }}
  resource_group_name = {{ .Values.ResourceGroup | quote }}
}

provider "kubernetes" {
  host                   = data.azurerm_kubernetes_cluster.cluster.kube_config[0].host
  client_certificate     = base64decode(data.azurerm_kubernetes_cluster.cluster.kube_config[0].client_certificate)
  client_key             = base64decode(data.azurerm_kubernetes_cluster.cluster.kube_config[0].client_key)
  cluster_ca_certificate = base64decode(data.azurerm_kubernetes_cluster.cluster.kube_config[0].cluster_ca_certificate)
}
{{ end }}
